#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#include "Common.hpp"
#include "Protocol.hpp"

#define MAX_BUFFER_SIZE 1024

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage: " << argv[0] << " server_ip server_port" << std::endl;
        return 1;
    }

    std::string server_ip = argv[1];
    int server_port = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "create socket error" << std::endl;
        return 2;
    }
    // 填充服务器地址信息
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_port);
    server_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());
    // client不需要显示的bind，tcp是面向连接的,connect底层会自动bind

    // 连接服务器
    if (connect(sockfd, CONV(&server_addr), sizeof(server_addr)) < 0)
    {
        std::cout << "connect error" << std::endl;
        return 3;
    }

    // 发送数据
    std::string message;
    while (true)
    {
        int x, y;
        char oper;
        std::cout << "input x, y, oper: ";
        std::cin >> x >> y >> oper;
        Request req(x, y, oper);

        // 1.序列化
        req.Serialize(message);

        // 2.Encode
        Encode(message);

        // 3.发送
        int n = ::send(sockfd, message.c_str(), message.size(), 0);
        if (n > 0)
        {
            char inbuffer[1024];

            // 4. 获得应答
            int m = ::recv(sockfd, inbuffer, sizeof(inbuffer), 0);
            if (m > 0)
            {
                inbuffer[m] = 0;
                std::string package = inbuffer;
                std::string content;
                // 5.Decode
                Decode(package, &content);

                // 6.反序列化
                Response resp;
                resp.Deserialize(content);
                // 7.得到结构化数据,打印结果
                resp.Print();
            }
            else
                break;
        }
    }

    ::close(sockfd);

    return 0;
}